<template>
  <div class="home">
    <div
      class="div-left div-edit"
      contenteditable="true"
      ref="canvas"
      @keydown="handleKeyDown"
    >
      <canvas id="canvas" :width="width" :height="height" />
    </div>
    <div class="div-left">
      <h1 class="h h1" v-show="over">
        Over!
      </h1>
      <h1 class="h h1">
        <!-- {{ judgeMent }} -->
        <!-- {{ lastKey() }} -->
        {{ judgeResult }}
        <!-- {{ keyData }} -->
      </h1>

      <!-- <h2 class="h h2">速度:</h2>
      <input v-model="speedStr" @change="handleChangeSpeed" /> -->
      <h2 class="h h2">曲谱名儿(点击切换到这首歌)</h2>
      <ul>
        <li v-for="(item, index) in rectGets" :key="index">
          <button @click="handleGetRects(item.rectId)" class="h btn2">
            {{ item.name }}
          </button>
        </li>
      </ul>
      <h2 class="h h2">Scores:{{ Scores }} Combo :{{ Combo }}</h2>
    </div>
  </div>
</template>

<script>
import { getAll, getRectById } from "./api";
export default {
  name: "Home",
  data() {
    return {
      // 获取的数值
      rectGets: [],
      interval: {},
      ctx: {},
      now: 0,
      over: false,
      width: 800,
      height: 800,
      rectNum: 1,
      roadMax: 4,
      roadWidth: 120,
      maxTest: 10,
      roadHeight: 800,
      maxHeight: 60,
      maxWidth: 10,
      speed: 1,
      speedStr: "",
      rectData: [{ x: 0, y: 0, w: 100, h: 10 }],
      keyData: [],
      keySet: [
        { key: 90, no: 0 },
        { key: 88, no: 1 },
        { key: 67, no: 2 },
        { key: 86, no: 3 },
        { key: 85, no: 4 }
      ],
      inter: 5,
      maxMinLength: 10000,
      maxAllowHeight: 10,
      judgeResult: "",
      baseJudge: [
        { name: "GOOD", score: 10, max: 100, no: 1, isCombo: false },
        { name: "GREAT", score: 200, max: 50, no: 2, isCombo: true },
        { name: "PERFECT", score: 500, max: 20, no: 3, isCombo: true }
      ],
      judgeMent: [],
      badJudge: {},
      Scores: 0,
      Combo: 0
    };
  },
  components: {},
  methods: {
    init() {
      console.log("start getCanvas");
      const canvas = document.getElementById("canvas");
      this.ctx = canvas.getContext("2d");
    },
    randomInt(x) {
      return Math.trunc(Math.random() * x);
    },
    drawBack() {
      for (let z = 0; z < this.keySet.length; z++) {
        const lineG = this.ctx.createLinearGradient(80, 80, 200, 200);
        lineG.addColorStop(0.5, "green");
        lineG.addColorStop(1, "blue");
        this.ctx.strokeStyle = lineG;
        this.ctx.lineWidth = 10;
        this.ctx.strokeRect(
          z * this.roadWidth,
          0,
          this.roadWidth,
          this.roadHeight
        );
      }
    },
    randomColor(x, y, z) {
      return (
        "rgb(" +
        this.randomInt(x) +
        "," +
        "0" +
        this.randomInt(y) +
        "," +
        this.randomInt(z) +
        "," +
        Math.random() +
        ")"
      );
    },
    fillRect(x, y, w, h) {
      this.ctx.fillRect(x, y, w, h);
    },
    strokeRect(x, y, w, h) {
      this.ctx.strokeRect(x, y, w, h);
    },
    handleKeyDown(e) {
      console.log(e.keyCode);
      if (this.countIfOver()) {
        return;
      }
      if (!this.judgeInSet(e.keyCode)) {
        console.log("wrong keyCode");
        this.setJudge(this.badJudge);
      } else if (!this.judgeIsLast(e.keyCode)) {
        this.setJudge(this.badJudge);
        console.log("last key is not it");
      } else if (this.keyData.length === 0) {
        console.log("game is over");
      } else {
        this.judge(e.keyCode, this.lastKey());
      }
    },
    setKeyData() {
      for (let i = 0; i < this.maxTest; i++) {
        this.keyData.push({
          no: this.randomInt(this.keySet.length),
          y: -this.randomInt(this.maxMinLength),
          v: 10
        });
      }
      this.keyData.sort((a, b) => {
        return a.y - b.y;
      });
    },
    drawRect() {
      if (this.keyData.length > 0) {
        for (const m of this.keyData) {
          // console.log(m);
          const lineG = this.ctx.createLinearGradient(80, 80, 200, 200);
          lineG.addColorStop(0.5, "green");
          lineG.addColorStop(1, "blue");
          this.ctx.fillStyle = lineG;
          this.fillRect(this.roadWidth * m.no, m.y, this.roadWidth, 5);
        }
      }
    },
    refreshRect() {
      if (this.keyData.length > 0) {
        for (const ss of this.keyData) {
          // ss.y += this.speed;
          for (let i = 0; i < this.speed; i++) {
            ss.y += 1;
          }
        }
        if (this.lastKey().y > this.roadHeight + this.maxAllowHeight) {
          this.setJudge(this.badJudge);
          this.keyData.pop();
        }
      }
    },

    countIfOver() {
      this.over = this.keyData.length === 0;
      return this.over;
    },
    lastKey() {
      if (this.keyData.length > 0) {
        return this.keyData[this.keyData.length - 1];
      } else {
        return { no: -1, y: -9999, v: -9999 };
      }
    },

    getJudgeByAbsHeight(absHeight) {
      const r = this.judgeMent.filter(e => {
        return e.max > absHeight;
      });
      if (r.length === 0) return this.badJudge;
      // 这种排序就是大的排在前面
      r.sort((a, b) => {
        return a.max - b.max;
      });

      console.log(r);
      return r[0];
    },
    judge(keyCode, lastKey) {
      const deltaHeight = this.roadHeight - lastKey.y;
      const absHeight = Math.abs(deltaHeight);
      console.log("abs is", absHeight);
      const judge = this.getJudgeByAbsHeight(absHeight);
      console.log("judge is", judge);
      this.setJudge(judge);
      if (judge.name !== "BAD") {
        this.keyData.pop();
      }
    },
    setResult(e) {
      this.judgeResult = e;
    },
    setOver() {},
    initJudge() {
      const judgeMent = this.baseJudge;

      judgeMent.push({
        name: "O",
        max: 0,
        score: 210,
        no: 4,
        ifCombo: true
      });
      judgeMent.push({
        name: "BAD",
        max: this.roadHeight,
        score: -10,
        no: 0,
        isCombo: false
      });
      judgeMent.sort((a, b) => {
        return b.max - a.max;
      });

      this.judgeMent = judgeMent;
      this.badJudge = judgeMent[0];
    },
    judgeInSet(keyCode) {
      return (
        this.keySet.filter(e => {
          return e.key === keyCode;
        }).length !== 0
      );
    },
    judgeIsLast(keyCode) {
      return (
        this.keySet.filter(e => {
          return e.key === keyCode && this.lastKey().no === e.no;
        }).length !== 0
      );
    },
    setJudge(e) {
      console.log(e);
      this.judgeResult = e.name;
      this.Scores += e.score;
      const isComboStrs = this.judgeMent.filter(e => {
        return e.isCombo;
      });
      if (isComboStrs.indexOf(e) !== -1) {
        this.Combo++;
      } else {
        this.Combo = 1;
      }
    },
    getAllRectInfos() {
      getAll().then(r => {
        this.rectGets = r;
      });
    },
    game() {
      this.over = false;
      this.Combo = 0;
      this.Scores = 0;
      this.initJudge();
      clearInterval(this.interval);
      this.interval = setInterval(() => {
        if (this.countIfOver()) {
          this.over = true;
          clearInterval(this.interval);
        }
        this.ctx.clearRect(0, 0, this.width, this.height);
        this.drawBack();
        this.refreshRect();
        this.drawRect();
      }, this.inter);
    },
    handleGetRects(id) {
      getRectById(id).then(res => {
        this.keyData = res;
        this.$refs.canvas.focus();
        this.game();
      });
    }
  },
  mounted() {
    this.$refs.canvas.focus();

    this.getAllRectInfos();

    this.init();
    this.setKeyData();
    this.game();

    // document.onkeydown = e => {

    // };
  }
};
</script>
<style scoped>
.h1 {
}
.h2 {
}
.div-left {
  width: 40%;
  display: inline-block;
}
</style>
